﻿using EarringsBackEnd.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EarringsBackEnd
{
    public partial class frmSearchEarrings : Form
    {
        private MasterDataManagement _dtMgmt = null;
        private List<PropertiesValue> _propValue = null;
        private string _styleId = string.Empty;
        private string _shpId = string.Empty;
        private string _colorId = string.Empty;
        private string[] _strArrHeader = null;

        public frmSearchEarrings()
        {
            InitializeComponent();
        }

        private void frmSearchEarrings_Load(object sender, EventArgs e)
        {
            //Load Data to ComboBox
            //Style
            this.GetEarringsStyle();

            //Shape
            this.GetEarringsShape();

            //Color
            this.GetEarringsColor();

            //Header Datagrid
            _strArrHeader = GlobalValue.gbStrArrEARSHeader;
        }

        private void GetEarringsStyle()
        {
            _dtMgmt = MasterDataManagement.InstanceCreation();
            _propValue = new List<PropertiesValue>();
            _propValue = (List<PropertiesValue>)_dtMgmt.GetMasterEarringConfig<PropertiesValue>(GlobalValue.SHRTYP_ERSTY);

            PropertiesValue styVal = new PropertiesValue();
            styVal.KeyId = "0";
            styVal.Name = "--กรุณาเลือกรูปแบบต่างหู--";
            _propValue.Insert(0, styVal);

            cboStyle.DataSource = _propValue;
            cboStyle.ValueMember = "KeyId";
            cboStyle.DisplayMember = "Name";
            cboStyle.SelectedIndex = 0;
        }

        private void GetEarringsShape()
        {
            _propValue = new List<PropertiesValue>();
            _propValue = (List<PropertiesValue>)_dtMgmt.GetMasterEarringConfig<PropertiesValue>(GlobalValue.SHRTYP_ERSHP);

            PropertiesValue shpVal = new PropertiesValue();
            shpVal.KeyId = "0";
            shpVal.Name = "--กรุณาเลือกรูปทรงต่างหู--";
            _propValue.Insert(0, shpVal);

            cboShape.DataSource = _propValue;
            cboShape.ValueMember = "KeyId";
            cboShape.DisplayMember = "Name";
            cboShape.SelectedIndex = 0;
        }

        private void GetEarringsColor()
        {
            _propValue = new List<PropertiesValue>();
            _propValue = (List<PropertiesValue>)_dtMgmt.GetMasterEarringConfig<PropertiesValue>(GlobalValue.SHRTYP_JWCOR);

            PropertiesValue colVal = new PropertiesValue();
            colVal.KeyId = "0";
            colVal.Name = "--กรุณาเลือกสีต่างหู--";
            _propValue.Insert(0, colVal);

            cboColor.DataSource = _propValue;
            cboColor.ValueMember = "KeyId";
            cboColor.DisplayMember = "Name";
            cboColor.SelectedIndex = 0;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            this.ClearValue();

            //Where StyleId
            string whereStyleId = string.Empty;
            if (!string.IsNullOrEmpty(_styleId))
            {
                whereStyleId = " WHERE er.Er_Style = " + _styleId;
            }
            //Where ShapeId
            string whereShapeId = string.Empty;
            if (!string.IsNullOrEmpty(_shpId))
            {
                whereShapeId = " WHERE er.Er_Shape = " +_shpId ;
            }
            //Where ColorId
            string whereColorId = string.Empty;
            if (!string.IsNullOrEmpty(_colorId))
            {
                whereColorId = " WHERE er.Er_Color = " + _colorId;
            }

            StringBuilder strSql = new StringBuilder();
            strSql.Append(" SELECT ROW_NUMBER()OVER(ORDER BY tb.Er_Code ) AS [No], tb.Er_Code, tb.Er_Name FROM");
            //strSql.Append(" , tb.Er_Styles_Name, tb1.Er_Shape_Name, tb2.Er_Color_Name");
            //strSql.Append(" , tb.Er_Gemstone, tb.FolderImg, tb.Er_Image_Front FROM");
            strSql.Append("(SELECT Er_Code,Er_Name,Config_NameTh AS [Er_Styles_Name],Er_Gemstone,Config_Name AS [FolderImg],Er_Image_Front FROM Earrings er ");
            strSql.Append(" INNER JOIN EarringsConfig erConf ON er.Er_Style = erConf.Config_Id ");
            strSql.Append(whereStyleId).Append(") tb");
            strSql.Append(" INNER JOIN");
            strSql.Append(" (SELECT Er_Code,Er_Shape,Config_NameTh AS [Er_Shape_Name] FROM Earrings er ");
            strSql.Append(" INNER JOIN EarringsConfig erConf ON er.Er_Shape = erConf.Config_Id ");
            strSql.Append(whereShapeId).Append(") tb1");
            strSql.Append(" ON tb.Er_Code = tb1.Er_Code");
            strSql.Append(" INNER JOIN");
            strSql.Append(" (SELECT Er_Code,Config_NameTh AS [Er_Color_Name] FROM Earrings er ");
            strSql.Append(" INNER JOIN EarringsConfig erConf ON er.Er_Color = erConf.Config_Id ");
            strSql.Append(whereColorId).Append(") tb2");
            strSql.Append(" ON tb.Er_Code = tb2.Er_Code");

            StringBuilder strWhere = new StringBuilder();
            if (!string.IsNullOrEmpty(txtErCode.Text))
            {
                strWhere.Append(" WHERE tb.Er_Code = '");
                strWhere.Append(txtErCode.Text).Append("'");
            }

            if(!string.IsNullOrEmpty(txtErName.Text))
            {
                if (string.IsNullOrEmpty(strWhere.ToString()))
                {
                    strWhere.Append(" WHERE ");
                }
                else
                {
                    strWhere.Append(" AND ");
                }
                strWhere.Append(" tb.Er_Name LIKE '%");
                strWhere.Append(txtErName.Text).Append("%'");
            }

            if (!string.IsNullOrEmpty(txtGemstone.Text))
            {
                if (string.IsNullOrEmpty(strWhere.ToString()))
                {
                    strWhere.Append(" WHERE ");
                }
                else
                {
                    strWhere.Append(" AND ");
                }
                strWhere.Append(" tb.Er_Gemstone LIKE '%");
                strWhere.Append(txtGemstone.Text).Append("%'");
            }
            //Concact Sql String

            strSql.Append(strWhere);

            DataTable dtResult = SqlClientUtility.ExecuteDataTable(CommandType.Text, strSql.ToString());

            this.GenDataToGridView(dtResult);
        }

        private void GenDataToGridView(DataTable result)
        {
            
            dtgvEarring.DataSource = result;

            this.InitializeDataGridView();

            //this.LoadImageToDataGrid(result);
        }
        private void InitializeDataGridView()
        {
            //Set Header Grid
            for (int intIndex = 0; intIndex < dtgvEarring.Columns.Count; intIndex++)
            {
                dtgvEarring.Columns[intIndex].HeaderText = _strArrHeader[intIndex];
            }

            DataGridViewImageColumn modiCol = new DataGridViewImageColumn();
            modiCol.DataPropertyName = "Modify";
            modiCol.Width = 50;
            modiCol.HeaderText = "แก้ไข";
            modiCol.Image = EarringsBackEnd.Properties.Resources.Edit;
            modiCol.ImageLayout = DataGridViewImageCellLayout.Normal;
            dtgvEarring.Columns.Insert(dtgvEarring.Columns.Count, modiCol);

            DataGridViewImageColumn delCol = new DataGridViewImageColumn();
            delCol.DataPropertyName = "Del";
            delCol.Width = 50;
            delCol.HeaderText = "ลบ";
            delCol.Image = EarringsBackEnd.Properties.Resources.Del;
            delCol.ImageLayout = DataGridViewImageCellLayout.Normal;
            dtgvEarring.Columns.Insert(dtgvEarring.Columns.Count, delCol);

            dtgvEarring.Columns[0].Width = 70;
            dtgvEarring.Columns[1].Width = 120;
            dtgvEarring.Columns[2].Width = 200;
            dtgvEarring.Columns[3].Width = 70;
            dtgvEarring.Columns[4].Width = 70;
        }

        private void LoadImageToDataGrid(DataTable result)
        {
            //
            int i = 1;
            foreach (DataRow row in result.Rows)
            {
                string path = Path.Combine(Resources.EarringsPath,SqlClientUtility.GetString(row,"FolderImg",""));
                path = Path.Combine(path, SqlClientUtility.GetString(row, "Er_Image_Front", ""));
                Image img = Image.FromFile(path);

                DataGridViewImageCell DGic = new DataGridViewImageCell();
                DGic.Value = img;

                dtgvEarring[1,i] = DGic;
                i++;
            }

        }

        private void cboStyle_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboStyle.SelectedIndex > 0)
            {
                PropertiesValue styVal = cboStyle.SelectedItem as PropertiesValue;
                _styleId = styVal.KeyId.ToString();
            }
        }

        private void cboShape_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboShape.SelectedIndex > 0)
            {
                PropertiesValue shpVal = cboShape.SelectedItem as PropertiesValue;
                _shpId = shpVal.KeyId.ToString();
            }
        }

        private void cboColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboColor.SelectedIndex > 0)
            {
                PropertiesValue colorVal = cboColor.SelectedItem as PropertiesValue;
                _colorId = colorVal.KeyId.ToString();
            }
        }

        private void dtgvEarring_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int rowIndex = e.RowIndex;
            DataGridViewRow row = dtgvEarring.Rows[rowIndex];

            int colIndex = e.ColumnIndex;
            DataGridViewColumn col = dtgvEarring.Columns[colIndex];

            string erCode = row.Cells[1].Value.ToString();

            if (col.HeaderText.ToString() == "แก้ไข" && !string.IsNullOrEmpty(row.Cells[1].Value.ToString()))
            {
                frmEarringMaster erMaster = new frmEarringMaster(erCode);
                erMaster.ShowDialog();
            }
            else if (col.HeaderText.ToString() == "ลบ" && !string.IsNullOrEmpty(row.Cells[2].Value.ToString()))
            {
                //ลบข้อมูล                

                DialogResult result = MessageBox.Show("คุณต้องการลบข้อมูลต่างหู รหัส: " + erCode + " หรือไม่?", "ยืนยัน", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    this.DeteleEarringsData(erCode);
                    MessageBox.Show("ลบเรียบร้อย");
                }
                else if (result == DialogResult.No)
                {
                    dtgvEarring.ClearSelection();
                }                
            }
        }

        private void DeteleEarringsData(string delErCode)
        {
            SqlParameter[] sqlParams = new SqlParameter[] 
                {
                    new SqlParameter("@Er_Code", delErCode)
                };
            //แก้ไขเป็น update status
            _dtMgmt = MasterDataManagement.InstanceCreation();
            _dtMgmt.DeleteEarringData(sqlParams);
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.ClearValue();

        }

        private void ClearValue()
        {
            foreach (Control ctl in tblLayout.Controls)
            {
                TextBox tb = ctl as TextBox;

                if (tb != null)
                {
                    tb.Clear();
                }
            }

            cboShape.SelectedIndex = 0;
            cboStyle.SelectedIndex = 0;
            cboColor.SelectedIndex = 0;

            //Clear Grid
            dtgvEarring.Rows.Clear();

            //foreach (DataGridViewRow row in dtgvEarring.Rows)
            //{
            //    dtgvEarring.Rows.Remove(row);
            //} 

        }
    }
}
